import fw from './framework.js'

function createProgram(data, param = {}, callbackFn) {
  var posX = param.posX;
  var posY = param.posY;
  var ajaxOpts = {
    programTemplateId: 0,
    name: '小程序专用节目',
    canvasHeight: posY || 1080,
    canvasWidth: posX || 1920,
    canvasBgColor: '#FFFFFF',
    canvasBgImage: null,
    playDuration: '23:59:59',
    programType: 'general', //节目类型,默认普通类型
    thumbnail: '',
    remark: '这是小程序里面特殊定制的节目',
    actionScope: "", // 公有私有，默认私有
    attrDuration: 0,
    attrType: '',
    attrData: [],
    programComponent: [],
    pageShots: fw.getPageShotsParam()
  };
  switch (data.type) {
    case 'image':
    case 'video':
      ajaxOpts.programComponent.push(getNewComponent(data, 'media', posX, posY))
      break;
    case 'qrcode':
      ajaxOpts.programComponent.push(getNewComponent(data, 'qrcode', posX, posY))
      break;
    case 'text':
      ajaxOpts.programComponent.push(getNewComponent(data, 'text', posX, posY))
      break;
  }
  fw.ajax('program/v2/create', ajaxOpts).then(function(res) {
    if(res.code == 0){
      quickPublish(res.data, param, callbackFn);
    }else{
      wx.showToast({
        title:'发布发生异常，请重试。',
        duration:2000
      });
    }
  })
}

function quickPublish(prmData, param, callbackFn) {
  var timeRange = [new Date(2018, 12, 12, 0, 0), new Date(2018, 12, 12, 23, 59)];
  var scheduleData = {
    "name": "",
    "remark": "",
    "level": 2,
    "channelType": "DEFAULT",
    "channelSchedulePeriodInfos": [{
      "programGroupPlayMethod": 1,
      "playStartTime": "每日 00:00",
      "playStartCrontab": "0 0 * * *",
      "playEndTime": "每日 23:59",
      "playEndCrontab": "59 23 * * *",
      "type": 1,
      "periodType": 1,
      "startTime": fw.moment().format('YYYY-MM-DD')+' 00:00:00',
      "endTime": fw.moment().add(5, 'years').format('YYYY-MM-DD')+' 23:59:59',
      "channelPlayProgramGroupInfos": []
    }]
  };
  var getCron = function(time) {
    var hour = parseInt(time.split(' ')[1].split(':')[0]);
    var minute = parseInt(time.split(' ')[1].split(':')[1]);
    // {0 分} {1 时} 0 0 {2 [周日-周六][1-7]}
    return fw.format('{0} {1} * * *', minute, hour)
  };
  scheduleData.name = prmData.name + '的排期';
  scheduleData.channelSchedulePeriodInfos[0].channelPlayProgramGroupInfos = [{
    "programId": prmData.id,
    "seq": 1
  }];
  scheduleData.channelSchedulePeriodInfos[0].playStartTime = '每日 ' + fw.moment(timeRange[0]).format('HH:mm');
  scheduleData.channelSchedulePeriodInfos[0].playEndTime = '每日 ' + fw.moment(timeRange[1]).format('HH:mm');
  scheduleData.channelSchedulePeriodInfos[0].playStartCrontab = getCron(scheduleData.channelSchedulePeriodInfos[0].playStartTime);
  scheduleData.channelSchedulePeriodInfos[0].playEndCrontab = getCron(scheduleData.channelSchedulePeriodInfos[0].playEndTime);
  var publishAjaxData = {
    "channelId": '',
    "terminals": [param.terminalId],
    "classifies": [],
    "tags": [],
    "publishTerminalType": 1,
    "isForce": true // 默认不校验横竖屏
  };
  var publishFail = function(){
    // todo  此处处理失败的情况。
  };
  fw.ajax('channel/v2/create', scheduleData).then(function(cRes) {
    if (cRes.code == 0) {
      publishAjaxData.channelId = cRes.data.id;
      fw.ajax('channelPublish/target/v2/publish', publishAjaxData).then(pRes => {
        if (pRes.code == 0) {
          callbackFn(prmData);
        }else{
          // 发布失败，请重试
          // 删除排期
          if(pRes.code==1003){
            wx.showToast({
              title:'发布的内容和屏幕方向不一致，请调整屏幕方向。',
              duration:2000
            });
          }else{
            wx.showToast({
              title:'发布到屏幕失败，请重试。',
              duration:2000
            });
          }
          fw.ajax('channel/v2/delete',{id:res.data.id}).then(function(chRes){
            if(chRes.code == 0){
              // 删除节目？
              fw.ajax('program/delete',{id:prmData.id}).then(function(prmRes){
                  if(prmRes.code == 0){
                    publishFail();
                  }else{
                    publishFail();
                  }
              });
            }else{
              publishFail();
            }
          })
        }
      });
    }else{
      wx.showToast({
          title:'发布失败，请重试。',
          duration:2000
      });
      fw.ajax('program/delete',{id:prmData.id}).then(function(prmRes){
        if(prmRes.code == 0){
          publishFail();
        }else{
          publishFail();
        }
      });
    }
  });
}

function updateProgram(data, param = {}, callbackFn) {
  readProgram(param.programId, function(prmDataRes) {
    var hasComponent = false;
    var newPrmData = JSON.parse(JSON.stringify(prmDataRes.data||prmDataRes));
    if (param.type == 'add') {
      (prmDataRes.data || prmDataRes).programComponent.forEach(function(component, i) {
        if ((data.type == 'image' || data.type == 'video') && component.type == 'media') {
          hasComponent = true;
          newPrmData.programComponent[i].componentParam.res.push(getResource(data, 'media', param.posX, param.posY))
        }
        if (data.type == 'qrcode'  && component.type == 'image') {
          hasComponent = true;
          newPrmData.programComponent[i].componentParam.res = [getResource(data, 'image', param.posX, param.posY)];
        }
        if (data.type == 'text' && component.type == 'text') {
          hasComponent = true;
          // newPrmData.programComponent[i].componentParam.res.push(self.getResource(data, 'text'))
          newPrmData.programComponent[i].componentParam.res = [getResource(data, 'text', param.posX, param.posY)]; // 目前文本只支持一个
        }
      });
      if (!hasComponent) {
        if (data.type == 'image' || data.type == 'video') {
          newPrmData.programComponent.push(getNewComponent(data, 'media', param.posX, param.posY))
        }
        if (data.type == 'text') {
          newPrmData.programComponent.push(getNewComponent(data, 'text', param.posX, param.posY))
        }
        if (data.type == 'qrcode') {
          newPrmData.programComponent.push(getNewComponent(data, 'image', param.posX, param.posY))
        }
      }
    } else if (param.type == 'delete') {
      (prmDataRes.data || prmDataRes).programComponent.forEach(function(component, i) {
        if (component.type == data.componentType) {
          if (component.componentParam.res.length == 1) {
            newPrmData.programComponent.splice(i, 1);
          } else {
            newPrmData.programComponent[i].componentParam.res.splice(data.index, 1);
          }
        }
      })
    }
    newPrmData.pageShots = fw.getPageShotsParam();
    // newPrmData.updateStamp = null;
    newPrmData.canvasHeight = param.posY || newPrmData.canvasHeight;
    newPrmData.canvasWidth = param.posX || newPrmData.canvasWidth;
    updateProgramByData(newPrmData, function (updatePrmRes){
      callbackFn(updatePrmRes);
    });
  })
}

function updateProgramByData(data,callbackFn){
  if(data.programComponent.length == 0 && fw.terminal.get().id){
    fw.cleanPublishContent(fw.terminal.get().id,function(){
      if(callbackFn)callbackFn(data);
    });
  }else{
    fw.ajax('program/v2/update', data).then(function (updatePrmRes) {
      if(updatePrmRes.code ==0){
        callbackFn(updatePrmRes.data);
      }else{
        wx.showToast({
          title:'更新发生异常，请重试。',
          duration:2000
        });
        callbackFn(null);
      }
    })
  }
}

function getNewComponent(data, type, posX, posY) {
  switch (type) {
    case 'media':
      return {
        "id": null,
        "w": posX,
        "h": posY,
        "x": 0,
        "y": 0,
        "type": "media",
        "level": 101,
        "bgColor": "#1e791f",
        "componentParam": {
          "opts": {
            "time": 8
          },
          "res": [getResource(data, type, posX, posY)]
        },
        "componentOtherParam": {},
        "thirdPartyParam": null
      };
    case 'image':
      return {
        "id": null,
        "w": 300,
        "h": 300,
        "x": (parseInt(posX)-300-50),
        "y": (parseInt(posY)-300-50),
        "type": "image",
        "level": 103,
        "bgColor": "#1e791f",
        "componentParam": {
          "opts": {
            "transformer": "Default",
            "time": 8
          },
          "res": [getResource(data, type, posX, posY)]
        },
        "componentOtherParam": {},
        "thirdPartyParam": null
      };
    case 'text':
      return {
        "id": null,
        "w": posX,
        "h": 145,
        "x": 0,
        "y": parseInt(posY) - 145,
        "type": "text",
        "level": 102,
        "bgColor": "#b39e1d",
        "componentParam": {
          "opts": {
            "type": "Marquee",
            "color": "#FFFFFF",
            "fontSize": 18,
            "bg": "rgba(0, 0, 0, 0.4)",
            "fontWeight": "常规",
            "font": "微软雅黑",
            "time": 1,
            "ScrollSpeed": "6",
            "direction": "3"
          },
          "res": [getResource(data, type, posX, posY)]
        },
        "componentOtherParam": {},
        "thirdPartyParam": null
      };

    default:
      break;

  }
}

function getResource(data, type, posX, posY) {
  var res = data.res.data || data.res;
  return {
    "fe_guid": "guid" + (new fw.GUID().newGUID()),
    "resourceId": res.id,
    "name": res.name || '',
    "type": data.type == 'qrcode' ? 'image' : data.type,
    "time": "00:00:08",
    "_ui_show": res.data
  }
}

function readProgram(programId, callbackFn) {
  fw.ajax('program/v2/read', {
    id: programId
  }).then(function(res) {
    if (callbackFn) {
      callbackFn(res.data);
    }
  })
}

module.exports = {
  read: readProgram,
  update: updateProgram,
  create: createProgram,
  updateProgramByData: updateProgramByData
}